package top.sdaily.business.service.crm.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.sdaily.core.mybatis.Conditions;
import top.sdaily.core.mybatis.Page;
import top.sdaily.core.utils.IdGeneratorUtils;
import top.sdaily.business.mapper.crm.CustomerMapper;
import top.sdaily.business.model.crm.Customer;
import top.sdaily.business.service.crm.CustomerService;
import top.sdaily.web.exception.FailedException;

import java.util.Date;
import java.util.List;

/**
 * Created by tsujishiki on 2017/2/7.
 */
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    CustomerMapper customerMapper;

    @Override
    public List<Customer> getPageCustomer(Page page) {
        List<Customer> pageResult = customerMapper.findList(new Conditions(Customer.class).page(page));
        return pageResult;
    }

    @Override
    public Customer getCustomerById(String id) {
        return customerMapper.findOne(new Conditions(Customer.class).id(id));
    }

    @Override
    public int insertCustomer(Customer customer) {
        Customer tmpCustomer = customerMapper.findOne(new Conditions(Customer.class).eq("customer_code", customer.getCustomerCode()));
        if(tmpCustomer != null) {
            throw new FailedException("客户编号已存在");
        }
        customer.setPkid(IdGeneratorUtils.fresh());
        return customerMapper.insert(customer);
    }

    @Override
    public int updateCustomer(Customer customer) {
        customer.setUpdatedate(new Date());
        return customerMapper.update(customer);
    }

    @Override
    public List<Customer> getAllEnabledCustomer(String condition) {
        // return customerMapper.findList(new Conditions(Customer.class).eq("isdeleted", "1").addOrderBy("createdate").sortDesc());
        if (condition != null && !"".equals(condition) && !"undefined".equals(condition)) {
            condition = "";
        }
        return customerMapper.findEnabledCustomer(condition);
    }
}
